package com.example.campusannouncement.controller;

import com.example.campusannouncement.service.AnnouncementService;
import com.example.campusannouncement.entity.Announcement;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/circuit-test")
public class CircuitBreakerTestController {
    private static final Logger logger = LoggerFactory.getLogger(CircuitBreakerTestController.class);

    @Autowired
    private CircuitBreakerFactory circuitBreakerFactory;

    @Autowired
    private AnnouncementService announcementService;

    @Autowired
    private ObjectMapper objectMapper;

    @GetMapping("")
    public String testPage() {
        return "circuit-test";
    }

    @GetMapping("/search")
    @ResponseBody
    public String searchWithCircuitBreaker(@RequestParam(required = false) String query,
                                         @RequestParam(defaultValue = "0") int page,
                                         @RequestParam(defaultValue = "10") int size) {
        return circuitBreakerFactory.create("database-service").run(
            () -> {
                try {
                    logger.info("执行数据库查询，关键词: {}, page: {}, size: {}", query, page, size);
                    
                    // 如果没有查询关键词，抛出异常
                    if (query == null || query.trim().isEmpty()) {
                        throw new IllegalArgumentException("请输入搜索关键词");
                    }

                    // 执行数据库查询
                    PageRequest pageRequest = PageRequest.of(page, size);
                    Page<Announcement> announcements = announcementService.searchAnnouncements(query, pageRequest);
                    
                    // 构建响应数据
                    Map<String, Object> response = new HashMap<>();
                    response.put("content", announcements.getContent());
                    response.put("totalElements", announcements.getTotalElements());
                    response.put("totalPages", announcements.getTotalPages());
                    response.put("currentPage", announcements.getNumber());
                    response.put("size", announcements.getSize());
                    
                    // 转换为JSON字符串
                    return objectMapper.writeValueAsString(response);
                } catch (JsonProcessingException e) {
                    logger.error("JSON转换失败", e);
                    throw new RuntimeException("数据处理失败", e);
                }
            },
            throwable -> {
                logger.error("数据库查询失败，触发降级", throwable);
                Map<String, Object> fallback = new HashMap<>();
                fallback.put("error", true);
                fallback.put("message", throwable instanceof IllegalArgumentException ? 
                    throwable.getMessage() : "服务暂时不可用，请稍后再试（降级响应）");
                try {
                    return objectMapper.writeValueAsString(fallback);
                } catch (JsonProcessingException e) {
                    return "{\"error\":true,\"message\":\"服务暂时不可用，请稍后再试\"}";
                }
            }
        );
    }
} 